# configure-ftp.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
package CCNCore::Provision::phones_polycom;
use strict;
use warnings;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;
use CCN::TimeOffset;

sub run()
{
    my $self = shift;
    return unless $self->p->is_a_file_server;

    $self->PACKAGE ('unzip');

    mkdir CCNCore::Home::config.'/local/loads';
    mkdir CCNCore::Home::config.'/local/loads/polycom';

    my %polycomsip = ();
    my %polycomboot = ();

    $self->sql_do_for(<<'SQL',$self->p->server_pk,
        SELECT  pool.pk, pool.enterprise, enterprise.salt, pool.timezone, pool.timeformat,
                pool.expire, pool.cp_cluster, pool.px_cluster
        FROM pool, enterprise
        WHERE pool.pk IN (SELECT pool FROM pool_server WHERE server = ? AND role = 'file')
        AND enterprise.pk = pool.enterprise;
SQL
    sub
    {
        my ($POOL_pk,$ENTERPRISE_pk,$SALT,$tz_name,$CLOCK_24,$REGISTER_EXPIRE,$cp_cluster,$register_cluster) = @_;

        $tz_name = $self->sql_get(q(SELECT timezone FROM systems WHERE pk = ?),$self->p->system_pk)
            if not defined $tz_name;
        $tz_name = 'UTC' if not defined $tz_name;
        my $GMT_OFFSET = CCN::TimeOffset::time_offset($tz_name);
        my $GMT_OFFSET_SEC = 3600*${GMT_OFFSET};

        $REGISTER_EXPIRE ||= 60;

        $self->sql_do_for(<<'SQL',$POOL_pk,
            SELECT pk, mac, polycomsip, polycomboot
            FROM phone WHERE type = 'polycom' AND pk = ?
SQL
        sub
        {
            my ($phone_pk,$MAC,$POLYCOM_SIP,$POLYCOM_BOOT) = @_;
            $MAC = CCN::Text::mac_from_dotted($MAC);

            my $LINE_APPEARANCES    = '';
            my $SERVERS             = '';

            $polycomsip{$POLYCOM_SIP} = 1 if defined $POLYCOM_SIP;
            $self->warn ("Polycom SIP load not specified for MAC ${MAC}.")
                if not defined $POLYCOM_SIP;
            $POLYCOM_SIP ||= '';

            $polycomboot{$POLYCOM_BOOT} = 1 if defined $POLYCOM_BOOT;

            my $line = 0;

            $self->sql_do_for(<<'SQL',$phone_pk,
                SELECT rank, "number", label, keys, "login", "password"
                FROM "line" WHERE phone = ? ORDER BY rank ASC
SQL
            sub
            {
                my ($LINE,$NUMBER,$LABEL,$KEYS,$LOGIN,$password) = @_;
                $line++;

                $LABEL = $NUMBER if not defined $LABEL;

                # See db_ser.pm
                # my $password = substr($self->make_password(${ENTERPRISE_pk},${SALT},${LOGIN},'phone'),12,12);

                $LINE_APPEARANCES .= <<"EOT";
reg.$line.displayName="${LABEL}"
reg.$line.address="${LOGIN}"
reg.$line.label="${NUMBER}"
reg.$line.type="private"
reg.$line.thirdPartyName=""
reg.$line.auth.userId="${LOGIN}"
reg.$line.auth.password="${password}"
reg.$line.acd-login-logout="0"
reg.$line.acd-agent-available="0"
reg.$line.ringType="2"
reg.$line.lineKeys="${KEYS}"
reg.$line.callsPerLineKey=""
EOT

                my $REGISTER_SERVER = $self->p->make_cluster_name(${register_cluster},'px');

                my $REGISTER_TRANSPORT = 'DNSnaptr';
                my $REGISTER_PORT      = '';

                my $nb = 1;

                $LINE_APPEARANCES .= <<"EOT";
reg.$line.server.$nb.transport="${REGISTER_TRANSPORT}"
reg.$line.server.$nb.address="${REGISTER_SERVER}"
reg.$line.server.$nb.port="${REGISTER_PORT}"
reg.$line.server.$nb.expires="${REGISTER_EXPIRE}"
reg.$line.server.$nb.register="1"
reg.$line.server.$nb.retryTimeOut=""
reg.$line.server.$nb.retryMaxCount=""
reg.$line.server.$nb.expires.lineSeize=""
EOT
                    # TBD I do know this is not the proper way to do it.
                $SERVERS .= <<"EOT";
voIpProt.server.$nb.address="${REGISTER_SERVER}"
voIpProt.server.$nb.port="${REGISTER_PORT}"
voIpProt.server.$nb.transport="${REGISTER_TRANSPORT}"
voIpProt.server.$nb.expires="${REGISTER_EXPIRE}"
voIpProt.server.$nb.register="1"
voIpProt.server.$nb.retryTimeOut="0"
voIpProt.server.$nb.retryMaxCount="0"
voIpProt.server.$nb.expires.lineSeize="30"
EOT
            }); # for @lines

            my $XML_SERVER          = '';
            my $DIALPLAN_DIGITMAP   = '';

            $CLOCK_24 = 1 if not defined $CLOCK_24;
            $CLOCK_24 = 1 if $CLOCK_24 =~ /^t/i;
            $CLOCK_24 = 0 if $CLOCK_24 =~ /^f/i;

            # TBD FIXME
            my $SNTP_SERVER = $self->sql_get(q(SELECT server FROM pool_server WHERE role = 'dhcp' AND pool = ?),$POOL_pk);
            $SNTP_SERVER = $self->p->server_pk if not defined $SNTP_SERVER;

            $SNTP_SERVER = $self->primary_ip($SNTP_SERVER);

            my $context = {
                'XML_SERVER' => $XML_SERVER,
                'DIALPLAN_DIGITMAP' => $DIALPLAN_DIGITMAP,
                'CLOCK_24' => $CLOCK_24,
                'SNTP_SERVER' => $SNTP_SERVER,
                'SERVERS' => $SERVERS,
                'MAC' => $MAC,
                'LINE_APPEARANCES' => $LINE_APPEARANCES,
                'GMT_OFFSET_SEC' => $GMT_OFFSET_SEC,
            };

            foreach("/home/PlcmSpIp/${MAC}.cfg")
            {
                CAT $_, <<"EOT";
<?xml version="1.0" standalone="yes"?>
<APPLICATION APP_FILE_PATH="${POLYCOM_SIP}/sip.ld" CONFIG_FILES="${MAC}-phone.cfg, ${MAC}-sip.cfg" MISC_FILES="" LOG_FILE_DIRECTORY="log" OVERRIDES_DIRECTORY="" CONTACTS_DIRECTORY="contacts"/>
EOT
            }

            foreach("/home/PlcmSpIp/${MAC}-phone.cfg")
            {
                template(CCNCore::Home::manager.'/bin/template_polycom-phone.xml',$_,$context);
            }

            foreach("/home/PlcmSpIp/${MAC}-sip.cfg")
            {
                template(CCNCore::Home::manager.'/bin/template_polycom-sip.xml',$_,$context);
            }

            # YYY
#                 my $xmldirectory = <<"EOT";
# <item><fn>$name</fn><ct>$ext</ct><sd>$sd</sd></item>
# EOT


        }); # for @nbphones


        # YYY Generate XML directories  SEE POD
    }); # for @pools

    foreach(CCNCore::Home::config.'/local/bin/install-polycom.sh')
    {
        my $POLYCOMBOOT = join(' ',keys %polycomboot) || '';
        my $POLYCOMSIP  = join(' ',keys %polycomsip) || '';
        my $home_manager = CCNCore::Home::manager;
        my $home_config  = CCNCore::Home::config;

        CAT $_, copyright('#!/bin/sh').<<"EOT";
# This script unzips the firmware loads from Polycom and
# installs them in the proper location.

# For testing purposes
ROOT=

echo "Installing Polycom loads into \$ROOT/home/PlcmSpIp/"
for POLYCOMBOOT in ${POLYCOMBOOT};
do
    echo "Unzip bootrom \$POLYCOMBOOT"
    unzip -q -o "\$ROOT$home_config/local/loads/polycom/spip_ssip_bootrom_\${POLYCOMBOOT}.zip" \\
        bootrom.ld \\
        -d "\$ROOT/home/PlcmSpIp/" || exit 1
done
for POLYCOMSIP in ${POLYCOMSIP};
do
    echo "Unzip SIP load $POLYCOMSIP"
    mkdir -p "\$ROOT/home/PlcmSpIp/\$POLYCOMSIP"
    unzip -q -o "\$ROOT$home_config/local/loads/polycom/spip_ssip_sip_\${POLYCOMSIP}_sig.zip" \\
          sip.ld sip.ver SoundPointIPWelcome.wav 'SoundPointIPLocalization/*' \\
          -d "\$ROOT/home/PlcmSpIp/\$POLYCOMSIP" || exit 1
done

echo "Updating ownership"
chown -R PlcmSpIp /home/PlcmSpIp/

EOT

        IF_CHANGED $_ => "/bin/sh $_";
    }
}
1;